﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using RentAWorker.RIA.RentAWorkerDataService;

namespace RentAWorker.RIA
{
	public class TimeLine : Panel
	{
        private static readonly double HourWidth = 40.0;

		public static Rect ConvertTimeToPosition(Size hourDimension, DateTime startTime, DateTime endTime)
		{
			return new Rect(
				24 * hourDimension.Width * startTime.TimeOfDay.TotalSeconds / (24 * 60 * 60),
				0,
				24 * hourDimension.Width * (endTime - startTime).TotalSeconds / (24 * 60 * 60),
                hourDimension.Height);
		}

		protected override Size MeasureOverride(Size constraint)
		{
			var result = new Size();				// resulting size that the method will return
			Size hourDimension;						// size of a single hour in the timeline
			double desiredWidth = 0.0;				// helper variable for calculating the width desired by children

			// calculate height of result size
			result.Width = 24 * TimeLine.HourWidth;
            hourDimension = new Size(TimeLine.HourWidth, constraint.Height);

			// iterate over all internal children and call Measure for each of them.
			foreach (var child in this.Children.Cast<ContentPresenter>())
			{
                var rentalService = child.Content as RentalService;
                var position = TimeLine.ConvertTimeToPosition(hourDimension, rentalService.StartDate, rentalService.EndDate);
                child.Measure(new Size(position.Width, position.Height));
				desiredWidth = Math.Max(child.DesiredSize.Width, desiredWidth);
			}

			// width is infinite -> return the width desired by children
			result.Width = desiredWidth;

			return result;
		}

		protected override Size ArrangeOverride(Size arrangeBounds)
		{
			// size of a single hour in the timeline
			var hourDimension = new Size(arrangeBounds.Width / 24, arrangeBounds.Height);

			// iterate over all internal children and call Arrange for each of them.
			foreach (var child in this.Children.Cast<ContentPresenter>())
			{
                var rentalService = child.Content as RentalService;
                var position = TimeLine.ConvertTimeToPosition(hourDimension, rentalService.StartDate, rentalService.EndDate);
				child.Arrange(position);
			}

			return arrangeBounds;
		}
	}
}
